package cn.jtfadmin.base.lang.config.excel;

import cn.jtfadmin.base.lang.common.utils.RequestUtils;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class ExcelWeb {

    /**
     * 增加response header
     * @param excelName
     * @return
     */
    public static OutputStream addCurrentResposeHeader(String excelName){
        HttpServletResponse response = RequestUtils.getResponse();
        response.setCharacterEncoding("UTF-8");
        response.setHeader("content-Type", "application/vnd.ms-excel");
        response.setHeader("Access-Control-Expose-Headers", "Content-Disposition");//在跨域下前端拿到回应头
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(excelName+".xlsx", "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            // 不会发生 ignore
        }
        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
           throw new RuntimeException(e);
        }
        return outputStream;
    }
}
